﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using System.Runtime.Serialization;
using Logic;
using Social;

/// <summary>
/// interact with the Bit.ly API to shorten or expand url.
/// The current API version is 2.0.1
/// </summary>
public class Bitly
{
    /// <summary>
    /// All APIs require authentication credentials supplied as query arguments You can find your apiKey at http://bit.ly/account/your_api_key
    /// All APIs require a version identifier to be present.
    /// All APIs support an optional return format specifier (json  is the default response format. xml is also available).
    /// All APIs support an optional callback specifier for use with json return format.
    /// bit.ly currently limits API users to no more than five concurrent connections from a single IP address.
    /// </summary>
    public const string EXPAND_URL_FORMAT = "http://api.bit.ly/expand?version=2.0.1&shortUrl={0}&login={1}&apiKey={2}";
    public const string SHORTEN_URL_FORMAT = "http://api.bit.ly/shorten?version=2.0.1&longUrl={0}&login={1}&apiKey={2}";
    public const string GET_STATS_FORMAT = "http://api.bit.ly/stats?version=2.0.1&shortUrl={0}&login={1}&apiKey={2}";
    public const string USER_NAME = "dubi1g";
    public const string API_KEY = "R_dcfe9b2eb9c89b71631dcc76752eeb37";

    public class ExpandResult
    {
        public Results results;

        public class Results
        {
            public LongUrl longUrl;
        }

        public class LongUrl
        {
            public string longUrl;
        }

    }

    /// <summary>
    /// This class represent the jason object and collects the required data
    /// </summary>
    public class ShortenResult
    {
        public shortURL results;

        public class shortURL
        {
            public LongUrl LongUrl;
        }
        public class LongUrl
        {
            public string shortUrl;
        }
    }

    public static string GetLongURL(string shortURL)
    {
        string hash = shortURL.Replace("http://bit.ly/", "");

        string requestUrl = string.Format(EXPAND_URL_FORMAT, shortURL, USER_NAME, API_KEY);
        string res = GetWebResponse(requestUrl, 60000);
        res = res.Replace(hash, "longUrl");

        JavaScriptSerializer sr = new JavaScriptSerializer();

        ExpandResult result = sr.Deserialize<ExpandResult>(res);
        return result.results.longUrl.longUrl;
    }

    /// <summary>
    /// convert the json string to a managed class
    /// </summary>
    public static ContentServiceResponse< string> GetShortURL(string longURL)
    {
		var response = new ContentServiceResponse<string>();
        string requestUrl = string.Format(SHORTEN_URL_FORMAT, HttpUtility.UrlEncode(longURL), USER_NAME, API_KEY);
		try
		{
			string res = GetWebResponse(requestUrl, 60000);
			res = res.Replace(longURL, "LongUrl");
			JavaScriptSerializer sr = new JavaScriptSerializer();
			ShortenResult result = sr.Deserialize<ShortenResult>(res);
            response.Content =  result.results.LongUrl.shortUrl;
			response.ResultOption = ServiceResultOptions.Success;
		}
		catch (Exception ex)
		{
			response.SetException(ex);
		}

		return response;
    }

    public static string GetWebResponse(string url, int timeOut)
    {
        string resText = "";
        HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
        req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";

        req.Method = "GET";
        req.Timeout = timeOut;

        HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
        using (resp)
        {

            StreamReader sr = new StreamReader(resp.GetResponseStream());
            using (sr)
            {
                resText = sr.ReadToEnd();
            }
        }
        return resText;
    }

    public static string GetStats(string shortUrl)
    {
        string requestUrl = string.Format(GET_STATS_FORMAT, HttpUtility.UrlEncode(shortUrl), USER_NAME, API_KEY);
        string res = GetWebResponse(requestUrl, 60000);

        return "";
    }


}


